<?php
// +----------------------------------------------------------------------
// | 用户表
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;

class User extends Model
{
	//隐藏字段
	protected $hidden = ["password"];
	// 自动完成,
	protected $auto= ['nickname'];
	protected $insert = ['guid','spread_uid','spread_time','shop_id'];
	protected function setGuidAttr() {
        return get_uuid();
    }
    protected function setShopIdAttr($value) {
      	if($value) return $value;
       	if($scene = request()->param('scene')){
       		return model('user')->where('id',$scene)->value('shop_id') ?: 0;
       	}
       	return 0;
    }
	protected function setSpreadUidAttr($scene) {
        return  $scene ?: (request()->param('scene') ?: 0);
    }
	protected function setSpreadTimeAttr() {
        return request()->param('scene') ? date("Y-m-d H:i:s")  : '';
    }
	//自动转换名称格式
	public function setNicknameAttr($nickname) {
		return preg_replace_callback('/./u',function (array $match) {
		    return strlen($match[0]) >= 4 ? '' : $match[0];
		},$nickname);
    }
	//关联店铺信息，一对一关联
	public function shopInfo(){
        return $this->hasOne('shop','uid','id');
    }
    //关联vip表
	public function vipInfo(){
        return $this->hasOne('UserVip','uid','id');
    }
    //关联用户账单表，一对多
	public function userBill(){
        return $this->hasMany('UserBill','uid','id');
    }
    //关联用户账单表，一对多
	public function spreadUser(){
        return $this->hasMany('User','id','spread_uid');
    }
    //关联用户签到表，一对多
	public function userSignLog(){
        return $this->hasMany('UserSignLog','uid','id');
    }
	
	
	/**
     * 设置启用
     * @param type $ids
     * @param type $v
     * @return type
     */
	public function setEnable($ids,$v)
    {
    	return $this->where('id','in', $ids)->update(['is_enable' => $v]);
    }
    
	/**
     * 新增用户
     * @param type $data
     * @return type
     */
	public function addUser($data)
    {
		$this ->allowField(true) -> save($data);
		return json_decode($this,true);  
    }
    
    /**
     * 更新数据
     * @param type $data
     * @param type $where
     * @return type
     */
	public function updateInfo($data,$where)
    {
		return  $this ->allowField(true)  -> save($data,$where);
    }
	
	/**
     * 获取当前用户信息
     * @param type $phone
     * @return type
     */
	public function getInfo($uid = '')
    {
    	return self::with([
    		'vipInfo'=>function($query){
    			$query->with('levelInfo');
    		},
	    	'shopInfo'=>function($query){
	    		$query->field("id,uid,name,contacts,phone");
	    		$query->field("latitude,longitude,province,city,region,address_detail");
	    		$query->field("img,bgimg,certificate_photo");
	    	}
    	])
		->field('password,is_del,is_enable,add_time,unionid,land_type,land_time',true)
		->get( $uid === '' ? request()->userInfo['id'] : $uid);
    }
	
	/**
     *用户累积消费
     * @param type $phone
     * @return type
     */
	public function consume($uid = '',$shop_id=-1)
    {
    	$model = model('order');
    	$model = $model->where('uid',$uid);
    	$model = $model->where('is_pay',1);
    	$model = $model->where('pay_type','<>','brokerage');
    	if($shop_id!=-1) $model = $model->where('shop_id',$shop_id);
    	return $model->sum('pay_price');
    }
	
	
	/**
     * 获取我的推广
     * @param type $phone
     * @return type
     */
	public function getSpread($uid)
    {
    	return self::where("spread_uid",$uid)->count();
    }
	
	/**
     * 获取我的分享 - 单商户
     * @param type $phone
     * @return type
     */
	public function getShareList($uid,$month='')
    {
		if($month) {
			$month = $month.'-01';
			$month = $month ? " and date_format(add_time, '%Y%m') = date_format(DATE_SUB('$month', INTERVAL 0 MONTH),'%Y%m')" : "";
		}
		
    	$model = new self;
		$model = $model->alias('a');
		$model = $model->leftJoin("( 
			select uid
				,ROUND(sum(number ),1) as pay_num
				,ROUND(sum(brokerage ),1) as get_brokerage
			from xw_user_bill  where status =1 and pm = 0 and (title like '%购买%' or title like '%抵扣%' )
			".$month."
			group by uid 
		) b",'a.id = b.uid');
		$model = $model->leftJoin("( 
			select uid
				,ROUND(sum(number ),1) as get_num
				,ROUND(sum(brokerage ),1) as pay_brokerage
			from xw_user_bill  where status =1 and pm = 1 and title like '%回退%'
			".$month."
			group by uid 
		) c",'a.id = c.uid');
		$model = $model->where('a.spread_uid',$uid);
		$model = $model->field("a.nickname,ifnull(a.phone,'') phone,a.avatarUrl,a.id");
		$model = $model->field('ifnull(b.pay_num,0.0) - ifnull(c.get_num,0.0) as money');
		$model = $model->field('ifnull(b.get_brokerage,0.0) - ifnull(c.pay_brokerage,0.0) as brokerage');
		$model = $model->order('b.get_brokerage','desc');
		$userList = $model->select()->toArray();
		
		//总佣金
		$total_brokerage = model('user_bill')->alias('a')
			->leftJoin('user b','a.uid = b.id')
			->where('a.uid',$uid)
			->where('a.shop_id = b.shop_id')
			->where('a.status',1)
			->where('a.category','brokerage')
			->where('a.pm',1)
			->sum('number');
		
		//总推广数
		$total_spread = model('User')->where("spread_uid",$uid)->count();
		
		return compact('total_spread','total_brokerage','userList');
    }
    
    /**
     * 使用积分
     * @param type $phone
     * @return type
     */
	public function useIntegral($uid,$num=0,$price=0,$key='',$type=1)
    {
    	if($num<=0){ return true; }
		if($type = 1){
			$title =  '下单积分抵扣';
			$msg = '下单使用' . floatval($num) . '积分抵扣' . floatval($price) . '元';
		}
		$user = self::get($uid);
		if($user->userBill()->expend($title,$uid,'integral','deduction',$num,$key,$user['integral'],$msg)){
			$user->integral	= ['dec', $num];
			return $user->save();
		}else{
			return true;
		}
    }
    
    /**
     * 添加积分
     * @param type $phone
     * @return type
     */
	public function addIntegral($uid,$num=0,$key='',$type=1)
    {
    	if($num<=0){ return true; }
    	$t = 'give';
		if($type == 1){
			$title =  '下单赠送积分';
			$msg = '下单赠送' . floatval($num) . '积分！';
		}
		if($type == 2){
			$title =  '签到赠送积分';
			$msg = '签到赠送' . floatval($num) . '积分！';
		}
		if($type == 3){
			$t = 'back';
			$title =  '取消订单回退积分';
			$msg = '取消订单回退' . floatval($num) . '积分！';
		}
		$user = self::get($uid);
		if( $user->userBill()->income($title,$uid,'integral','gain',$num,$key,$user['integral'],$msg) ){
			$user->integral	= ['inc', $num];
			return $user->save();
		}else{
			return true;
		}
    }
    
      /**
     * 使用赠送余额
     * @param type $phone
     * @return type
     */
	public function useBalanceGift($uid,$num=0,$price=0,$key='',$type=1)
    {
    	if($num<=0){ return true; }
		if($type==1){
			$title = '下单使用赠送余额抵扣';
			$msg = '下单使用' . floatval($num) . '赠送余额抵扣' . floatval($price) . '元！';
		}
		$user = self::get($uid);
		$balance_gift = $user['balance_gift'];
		if($user->userBill()->expend($title,$uid,'balance_gift','deduction',$num,$key,$balance_gift,$msg)){
			$user->balance_gift	= ['dec', $num];
			return $user->save();
		}else{
			return true;
		}
    }
    
     /**
     * 添加赠送余额
     * @param type $phone
     * @return type
     */
	public function addBalanceGift($uid,$num=0,$key='',$type=1)
    {
    	if( $num<=0 ){ return true; }
    	$t = 'give';
		if($type==1){
			$title =  '下单获得赠送余额';
			$msg = '下单获得' . floatval($num) . '元赠送余额！';
		}
		$user = self::get($uid);
		$balance_gift = $user['balance_gift'];
		if($user->userBill()->income($title,$uid,'balance_gift',$t,$num,$key,$balance_gift,$msg)){
			$user->balance_gift	= ['inc', $num];
			return $user->save();
		}else{
			return true;
		}
    }
    
    /**
     * 使用余额
     * @param type $phone
     * @return type
     */
	public function useBalance($uid,$num=0,$key='',$type=1)
    {
    	if( $num<=0 ){ return true; }
		if( $type==1 ){
			$title = '下单使用余额';
			$msg = '下单使用' . floatval($num) . '元账号余额支付成功！';
		}
		$user = self::get($uid);
		if($user->userBill()->expend($title,$uid,'balance','pay_order',$num,$key,$user['balance'],$msg)){
			$user->balance	= ['dec', $num];
			return $user->save();
		}else{
			return true;
		}
    }
    
    /**
     * 添加佣金
     * @param type $phone
     * @return type
     */
	public function addBrokerage($uid,$num=0,$key='',$type=1)
    {
    	if( $num<=0 ){ return true; }
		if($type==1){
			$title =  '下级付款下单获得佣金';
			$msg = '下级付款下单获得' . floatval($num) . '元佣金！';
		}
		if($type==2){
			$title =  '下下级付款下单获得佣金';
			$msg = '下下级付款下单获得' . floatval($num) . '元佣金！';
		}
		if($type==3){
			$title =  '下级进货获得佣金';
			$msg = '下级进货获得' . floatval($num) . '元佣金！';
		}
		if($type==4){
			$title =  '下下级进货获得佣金';
			$msg = '下下级进货获得' . floatval($num) . '元佣金！';
		}
		if($type==5){
			$title =  '开单分佣获得佣金';
			$msg = '开单分佣获得' . floatval($num) . '元佣金！';
		}
		$user = self::get($uid);
		$brokerage = $user['brokerage'];
		if($user->userBill()->income($title,$uid,'brokerage','rake-back',$num,$key,$brokerage,$msg)){
			$user->brokerage	= ['inc', $num];
			return $user->save();
		}else{
			return true;
		}
    }
    
    /**
     * 使用佣金
     * @param type $phone
     * @return type
     */
	public function useBrokerage($uid,$num=0,$key='',$type=1)
    {
    	if($num<1){ return true; }
		if($type==1){
			$title = '下单使用佣金';
			$msg = '下单使用' . floatval($num) . '佣金支付成功！';
		}
		$user = self::get($uid);
		if($user->userBill()->expend($title,$uid,'brokerage','pay_order',$num,$key,$user['brokerage'],$msg)){
			$user->brokerage	= ['dec', $num];
			return $user->save();
		}else{
			return true;
		}
    }
    
    
	/**
     * TODO 返订单佣金
     * @param $order
     */
    public static function backOrderBrokerage($order,$is_save=true)
    {
		//TODO 判断订单是否已分佣金
    	if( $order['is_brokerage'] != 0 )  return 0;
        //TODO 获取购买商品的用户
        if( !$userInfo = self::getInfo($order['uid']) ){
        	return 0;
        }
        
        //店员收益
        $staff_profit = '';
        if($order['bill_id']){
     		$staff_profit = model('order_bill')->where('id',$order['bill_id'])->value('staff_profit');
     		if($staff_profit)  $staff_profit = json_decode($staff_profit,true);
     	}
        
       	//TODO 总数
        $total = 0; 	
        
       	//TODO-----------------------------------
     	//TODO------------ 一级返佣-------------
     	//TODO-----------------------------------
        if( !$spreadInfo = model('User')->getInfo( $userInfo['spread_uid'] ) ){
        	return $total;
        }  
        $level = $spreadInfo['vip_info']['level'];
        //TODO 计算公式
        $brokerage = 0;
        $staff_brokerage = 0;
     	$cartInfo = $order['info']['cartInfo'];
     	foreach($cartInfo as $key => $value){
     		//1.商品收益
     		$profit = model('goods_specs_profit')
     			->where('specs_id',$value['specs_id'])
     			->where('level',$level)
     			->find();
     		//2.分类收益	
     		if( !$profit ){
     			$profit = model('goods_cate_level')
     				->where('cate_id',$value['goods']['cate_id'])
     				->where('level',$level)
     				->find();
     		}		
     		//3.平台收益	
     		if( !$profit && !$profit = model('user_level')->where('level',$level)->find()){
     			return false;
     		}
     		//计算
     		$type = $profit['commission_one_type'] ?? 1;
			$fracture = $profit['commission_one'];
 			if( $type != 0 ){
 				$fracture = $fracture <= 0 ? 0 : ($fracture >10 ? 10 : $fracture);
   				$fracture = ($fracture / 10) * 
	   				($value['sale_price'] * $value['cart_num']) * 
	   				($order['pay_price'] - $order['freight_price']) / 
	   				$order['total_sale_price'];
 			}
 			
 			$total += round($fracture,2);
 			
 			//减去店员收益
     		if($staff_profit) {
     			foreach($staff_profit as $k=>$profit){
     				if($profit['specs_id'] == $value['specs_id']){
     					$staff_profit[$k]['fracture'] += $fracture = ($profit['scale'] / 100 ) * $fracture;
     				}
     			}
     		}
     		
     		$brokerage += round($fracture,2);
     	}
     	
     	//TODO 添加一级佣金
     	if($is_save && !$res = self::addBrokerage($spreadInfo["id"],$brokerage,$order['order_no']) ){
     		return false;
     	}
     
     	//TODO 添加员工收益
     	if( $is_save && $staff_profit ){
     		foreach($staff_profit as $key => $val){
     			if($val['fracture']){
     				if($uid = model('shop_staff')->where('id',$val['staff_id'])->value('uid') ){
     					self::addBrokerage($uid,$val['fracture'],$order['order_no'],5);
     				}
     			}
     		}
     	}
     	
     	//TODO-----------------------------------
     	//TODO------------ 二级返佣-------------
     	//TODO-----------------------------------
        if( !$spreadInfo = model('User')->getInfo( $spreadInfo['spread_uid'] ) ){
        	return $total;
        }
        $level = $spreadInfo['vip_info']['level'];
        //TODO 计算公式
        $brokerage = 0;
     	$cartInfo = $order['info']['cartInfo'];
     	foreach($cartInfo as $key => $value){
     		//1.商品收益
     		$profit = model('goods_specs_profit')
     			->where('specs_id',$value['specs_id'])
     			->where('level',$level)
     			->find();
     		//2.分类收益	
     		if( !$profit ){
     			$profit = model('goods_cate_level')
     				->where('cate_id',$value['goods']['cate_id'])
     				->where('level',$level)
     				->find();
     		}		
     		//3.平台收益	
     		if( !$profit && !$profit = model('user_level')->where('level',$level)->find()){
     			return false;
     		}
     		//计算
     		$type = $profit['commission_two_type'] ?? 1;
			$fracture = $profit['commission_two'];
 			if( $type == 0 ){
 				$brokerage += $fracture;
 			}else{
 				$fracture = $fracture <= 0 ? 0 : ($fracture >10 ? 10 : $fracture);
   				$brokerage += ($fracture / 10) * 
   					($value['sale_price'] * $value['cart_num']) * 
   					($order['pay_price'] - $order['freight_price']) / 
   					$order['total_sale_price'];
 			}
     	}
     	//TODO 添加二级佣金
     	$total += $brokerage = round($brokerage,2);
     	if( $is_save && !$res = self::addBrokerage($spreadInfo["id"],$brokerage,$order['order_no'],2)){
     		return false;
     	}
     	
     	return $total;
    }
    
    
    /**
     * TODO 返进货订单佣金
     * @param $order
     */
    public static function backPurchaseBrokerage($order, $is_save = true)
    {
    	$shop = model('shop')->get($order['shop_id']);

        //TODO 获取购买商品的用户
        if( !$userInfo = self::getInfo($shop['uid']) ){
        	return 0;
        }
        
       	//TODO 总数
        $total = 0; 	
        
       	//TODO-----------------------------------
     	//TODO------------ 一级返佣-------------
     	//TODO-----------------------------------
        if( !$spreadInfo = model('User')->getInfo( $userInfo['spread_uid'] ) ){
        	return $total;
        }
        $level = $spreadInfo['vip_info']['level'];
        $brokerage = 0;
        
        //TODO 收益方式
        $profit = model('goods_specs')->alias('a')
        		->leftJoin('goods b','a.goods_id = b.id')
        		->leftJoin('goods_cate_level c','c.cate_id = b.cate_id and c.level='.$level)
        		->leftJoin('goods_specs_profit d','a.id = d.specs_id and d.level='.$level)
        		->leftJoin('user_level e','e.level='.$level)
     			->where('a.id',$order['specs_id'])
     			->field("
     				ifnull(d.commission_one, 
     					ifnull(c.commission_one, 
     						ifnull(e.commission_one,0) 
     					) 
     				) as fracture
     			")
     			->field("ifnull(d.commission_one_type, 1) type")
     			->find();
     	//计算
 		$type = $profit['type'];
		$fracture = $profit['fracture'];
		if( $type == 0 ){
			$brokerage += $fracture;
		}else{
			$fracture = $fracture <= 0 ? 0 : ($fracture >10 ? 10 : $fracture);
			$brokerage += ($fracture / 10) * ($order['price'] * $order['num']);
		}
     	//TODO 添加一级佣金
     	$total = $brokerage = round($brokerage,2);
     	if( $is_save && !$res = self::addBrokerage( $spreadInfo["id"], $brokerage, $order['order_no'] ?? $order['id'],3) ){
     		return $total;
     	}
   
     	
     	//TODO-----------------------------------
     	//TODO------------ 二级返佣-------------
     	//TODO-----------------------------------
        if( !$spreadInfo = model('User')->getInfo( $spreadInfo['spread_uid'] ) ){
        	return true;
        }
        $level = $spreadInfo['vip_info']['level'];
        $brokerage = 0;
        //TODO 收益方式
        $profit = model('goods_specs')->alias('a')
        		->leftJoin('goods b','a.goods_id = b.id')
        		->leftJoin('goods_cate_level c','c.cate_id = b.cate_id and c.level='.$level)
        		->leftJoin('goods_specs_profit d','a.id = d.specs_id and d.level='.$level)
        		->leftJoin('user_level e','e.level='.$level)
     			->where('a.id',$order['specs_id'])
     			->field("
     				ifnull(d.commission_two, 
     					ifnull(c.commission_two, 
     						ifnull(e.commission_two,0) 
     					) 
     				) as fracture
     			")
     			->field("ifnull(d.commission_two_type, 1) type")
     			->find();
     	//计算
 		$type = $profit['type'];
		$fracture = $profit['fracture'];
		if( $type == 0 ){
			$brokerage += $fracture;
		}else{
			$fracture = $fracture <= 0 ? 0 : ($fracture >10 ? 10 : $fracture);
			$brokerage += ($fracture / 10) * ($order['price'] * $order['num']);
		}
     	//TODO 添加二级佣金
     	$total += $brokerage = round($brokerage,2);
     	if( $is_save && !$res = self::addBrokerage($spreadInfo["id"],$brokerage,$order['order_no']?? $order['id'],4)){
     		return false;
     	}
     	
     	return $total;
    }
    
}
